package com.googlecode.dgwt.client.dijit.base.widget;

import com.googlecode.dgwt.client.dijit.View;
import com.googlecode.dgwt.client.dojo.exception.DojoRuntimeException;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class ViewHandler extends WidgetHandler {

    private final View view; 
    
    
    public ViewHandler(View view) {
        this(view, null);
    }

    public ViewHandler(View view, WidgetHandler nextHandler) {
        super(nextHandler);
        this.view = view;
    }

    
    public final View getView(){
        return view;
    }
    
    @Override
    public void initialize(){
        if (view.getWidget().getParent() != null){
            throw new DojoRuntimeException(view, "Error when adding a view. The view widget already has a parent!");
        }
        getWidget().adopt(view.getWidget());
    }

    @Override
    public void doAttachChildren() {
        super.doAttachChildren();
        getWidget().childOnAttach(view.getWidget());
    }

    @Override
    public void doDetachChildren() {
        super.doDetachChildren();
        getWidget().childOnDetach(view.getWidget());
    }

    @Override
    public void onPostCreate() {
        super.onPostCreate();
        if (!getWidget().getElement().isOrHasChild(getView().getWidget().getElement())) {
            throw new DojoRuntimeException(view, "this view element is not a child of the parent widget!");
        }
    }

}
